// pages/law/detail/index.js

var WxParse = require('../../../wxParse/wxParse.js');
import util from '../../../utils/util';

var _longtapEventTime, _optEvent, _saveEvent={detail:{x:0, y:0}}, _userSay, _userFeedback, _screenWidth, _screenHeight, _searchInputCnt, _totalSearchedNo=0, _searchedIndex=-1, _SDKVersion;


function _getBookMarkSize(_item){
  var _result = _getBookMarkBlockSize(_item);
  _result.top = _item.offsetTop-_result.height-10;
  var _offsetX=20;
  if(_item.x > _screenWidth/2){
    _result.left = _screenWidth-_item.x-_offsetX; 
    _result.atleft = false;
  }else{
    _result.left = _item.x-_offsetX;
    _result.atleft = true;
  }
  return _result;
}

function _getBookMarkBlockSize(_item){
  var _width, _height;
  var _count = (_item.userSay || "书签").replace(/[\u4e00-\u9fa5]/g, "**").replace(/\s\S/g, "*").length;
  _height = _count*7*1.2 + 10;
  if(_item.x > _screenWidth/2){
    _width = _item.x-(_SDKVersion==0?0:40);
  }else{
    _width = _screenWidth-_item.x-20;
  }
  _height = Math.ceil(_height/_width)*16 + 12;
  return {
    width: _width,
    height: _height
  }
}


Page({
  data:{
    name: "",
    toView: 0,
    scrollTop: 0,
    scrollTopCal: 0,
    maskHide: true,
    dialogHide: true,
    userInfo: null,
    showOpt: false,
    hideBottomOpts: true,
    showCollectionBtn: false,
    showUnCollectionBtn: false,
    showErrorDialog: false,
    correctMaskHide: true,
    bookMarkMaskHide: true,
    newBookMarkMaskHide: true,
    showBookMarkDialog: false,
    showNewBookMarkDialog: false,
    searchShow: false,
    hasSearched: false,
    lastSearchInputCnt: "**&**&8&8*",
    showDeleteBtn: false,
    tabSelectIndex: 1,
    editBookMakrId: null,
    editBookMakrIndex: -1,
    newBookMarkOpt: true,
    userSay: "",
    userFeedback: "",
    content: "",
    bookmarks: null,
    detailInfo: {}
  },
  onLoad:function(options){
    var _search = options.search || "";
    var _tiaoNo = options.tiaoPosition || 0;
    if(!!_tiaoNo){
      this.setData({
        tiaoNo: "tiaoNo"+_tiaoNo
      });
    }

    var that = this;
    this.setData({
      name: options.name || "",
      id: options.id,
      maskHide: true,
      dialogHide: true
    });

    var _appInstance = getApp();
    var _globalData = _appInstance.globalData;
    this.setData({
      switchForVerify: !!_globalData.switchForVerify || false
    });

    wx.setNavigationBarTitle({
      title: options.name || "法条大全",
      success: function(res) {
        // success
      }
    });

    // 获取高度
    wx.getSystemInfo({
        success:function(res){
            that.setData({
                scrollHeight:res.windowHeight,
                dialogScrollHeight: res.windowHeight-100,
                phone: res.model
            });
            _SDKVersion = res.SDKVersion || 0;
            _screenWidth = res.screenWidth || res.windowWidth;
            _screenHeight = res.screenHeight || res.windowHeight;
        },
        fail: function(res){
          // wx.showToast({
          //   title: '获取失败',
          //   icon: 'loading',
          //   duration: 2000
          // });
        }
    });

    var _appInstance = getApp();
    var _globalData = _appInstance.globalData.userInfo;
    this.setData({
      userInfo: _globalData
    });
    
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });

    var _auth = util.genAuth();
    var that = this;

    // 获取法条详情
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/bd/law/detail`, //仅为示例，并非真实的接口地址
      data: {
        id: options.id,
        timestamp: _auth.timestamp,
        token: _auth.token
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        /*** 传值* 1. 类型type->'md/html'* 2. 介些内容data* 3. 指向对象-> page*/
        that.setData({
          publishTime: util.formatCommonShortTime(res.data.publishTime),
          effectiveTime: util.formatCommonShortTime(res.data.effectiveTime)
        });
        if(!!_search){
          var _reg = new RegExp(_search, 'g');
          res.data.content = res.data.content.replace(_reg, function($1){
            return '<em class="search">' + $1 + '</em>';
          })
        }
        that.setData({
          originContent: res.data.content
        });

        WxParse.wxParse('content', 'html', that.data.originContent, that);

        var _hasBian = /class="bian"\s*dataid="bian\d+/.test(res.data.mulu);
        that.setData({
          hasBian: _hasBian
        });
        var _mulu = res.data.mulu.replace(/<h2\s*class=.+?<\/h2>/, "");
        WxParse.wxParse('mulu', 'html', _mulu, that);

        wx.setNavigationBarTitle({
          title: res.data.name,
          success: function(res) {
          }
        });
        that.setData({
          toView: that.data.tiaoNo||0
        });

        res.data.effectiveTimeStr = util.formatCommonShortTime(res.data.effectiveTime);
        res.data.publishTimeStr = util.formatCommonShortTime(res.data.publishTime);
        // 10： 现行有效  20：失效  30：已被修改   40：尚未生效  50：部分失效
        switch(res.data.status){
          case 10:  res.data.statusStr="现行有效"; break;
          case 20:  res.data.statusStr="失效"; break;
          case 30:  res.data.statusStr="已被修改"; break;
          case 40:  res.data.statusStr="尚未生效"; break;
          case 50:  res.data.statusStr="部分失效"; break;
        }
        that.setData({
          detailInfo: {
            name: res.data.name,
            effectiveTimeStr: res.data.effectiveTimeStr,
            publishTimeStr: res.data.publishTimeStr,
            effectiveTimeStr: res.data.effectiveTimeStr,
            effectiveLevel: res.data.effectiveLevel,
            lawType: res.data.lawType,
            statusStr: res.data.statusStr,
            publishDepartment: res.data.publishDepartment
          }
        });

        // 获取书签
        wx.request({
          url: `${getApp().globalData.serverHost}/wx/get/user/law/bookmark`, //仅为示例，并非真实的接口地址
          data: {
            uid: that.data.userInfo.unionId,
            lid: that.data.id
          },
          method: "post",
          header: {
              'content-type': 'application/json'
          },
          success: function(res) {
            for(var i=0; i<res.data.length; i++){
              var _pos = _getBookMarkSize(res.data[i]);
              res.data[i].left = _pos.left;
              res.data[i].top = _pos.top;
              res.data[i].width = _pos.width;
              res.data[i].height = _pos.height;
              res.data[i].atleft = _pos.atleft;
              res.data[i].show = false;
            }

            var _arr = [];
            for(var i=0; i<20; i++){
              _arr.push({
                left: 0,
                top: 10000,
                width: 0,
                height: 0,
                userSay:"",
                hide: true
              });
            }
            var _concat = res.data.concat(_arr);

            that.setData({
              // bookmarks: res.data,
              innerBookmarks: _concat
            });
          },
          fail: function(res){
            console.log(res);
          }
        });
      },
      fail: function(res){
        console.log(res);
      }
    });

    // 获取用户是不是收藏此法条
    if(!!this.data.userInfo){
      wx.request({
        url: `${getApp().globalData.serverHost}/wx/check/user/collection`, //仅为示例，并非真实的接口地址
        data: {
          lid: this.data.id,
          uid: this.data.userInfo.unionId
        },
        method: "post",
        header: {
            'content-type': 'application/json'
        },
        success: function(res) {
          wx.hideToast();
          if(!!res.data){
            that.setData({
              showUnCollectionBtn: true
            });
          }else{
            that.setData({
              showCollectionBtn: true
            })
          }
        },
        fail: function(res){
          console.log(res);
        }
      })
    }

    // 在页面中定义激励视频广告
    this.videoAd = null

    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      this.videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-8a02b43999070412'
      })
      this.videoAd.onLoad(() => {})
      this.videoAd.onError((err) => {})
      this.videoAd.onClose((res) => {})
    }

    setTimeout(() => {
      // 用户触发广告后，显示激励视频广告
      if (this.videoAd) {
        this.videoAd.show().catch(() => {
          // 失败重试
          this.videoAd.load()
            .then(() => this.videoAd.show())
            .catch(err => {
              console.log('激励视频 广告显示失败')
            })
        })
      }
    }, 8000);
  },

  collection: function(){
    var that = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });

    // 获取列表
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/save/law/collection`, //仅为示例，并非真实的接口地址
      data: {
        uid: this.data.userInfo.unionId,
        lid: this.data.id
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          duration: 1000
        });
        that.setData({
          showUnCollectionBtn: true,
          showCollectionBtn: false
        })
      },
      fail: function(res){
        console.log(res);
      }
    })
  },
  uncollection: function(){
    var that = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    });

    // 获取列表
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/delete/law/collection`, //仅为示例，并非真实的接口地址
      data: {
        uid: this.data.userInfo.unionId,
        lid: this.data.id
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        wx.showToast({
          title: '取消收藏成功',
          icon: 'success',
          duration: 1000
        });
        that.setData({
          showUnCollectionBtn: false,
          showCollectionBtn: true
        })
      },
      fail: function(res){
        console.log(res);
      }
    })
  },
  showMulu: function(_event){
    this.setData({
      showOpt:true,
      hideBottomOpts: true
    });
    _longtapEventTime = _event.timeStamp;
    this.setData({
      maskHide: false,
      dialogHide: false
    });
  },
  showBookMark: function(_event){
    this.setData({
      newBookMarkMaskHide: false,
      showNewBookMarkDialog: true,
      userSay: ""
    });
    var _x = _optEvent.detail.x,
        _y = _optEvent.detail.y;
    _saveEvent = _optEvent;
    
    var _top, _left, _bottom, _right, _isLeft = true, _isTop = true;
    if(_x > _screenWidth/2){
      _isLeft = false;
      _right = _screenWidth-_x-6;
    }else{
      _left = _x -16;
    }
    if(_y > _screenHeight/3){
      _bottom = _screenHeight-_y-36;
      _isTop = false;
    }else{
      _top = _y+12;
    }
    
    var _posStr = "";
    if(_isTop && _isLeft){
      _posStr = 'top:' + _top + 'px;left:' + _left + 'px';
    }else if(_isTop && !_isLeft){
      _posStr = 'top:' + _top + 'px;right:' + _right + 'px';
    }else if(!_isTop && _isLeft){
      _posStr = 'bottom:' + _bottom + 'px;left:' + _left + 'px';
    }else if(!_isTop && !_isLeft){
      _posStr = 'bottom:' + _bottom + 'px;right:' + _right + 'px';
    }
    this.setData({
      newBookMarkDialogAtLeft: _isLeft,
      newBookMarkDialogAtTop: _isTop,
      posStr: _posStr
    });
  },
  hideMask: function(){
    this.setData({
      dialogHide: true
    });
    var that = this;
    setTimeout(function(){
      that.setData({
        maskHide: true
      });
    }, 400);
  },
  hideCorrectMask: function(){
    this.setData({
      showErrorDialog: false,
      correctMaskHide: true
    });
  },
  hideBookMarkMask: function(_event){
    this.setData({
      showBookMarkDialog: false,
      bookMarkMaskHide: true,
      showNewBookMarkDialog: false,
      newBookMarkMaskHide: true,
      hideBottomOpts: true,
      posStr: ""
    });
  },
  wxParseTagATap: function(_event){
    var _title = _event.currentTarget.dataset.title,
      _link = _event.currentTarget.dataset.c ||  _event.currentTarget.dataset.src, _position;
    if(!!_title && /^第*[一二三四五六七八九十百]+条$/.test(_title)){
      _position = util.getIndexFromChinse(_event.currentTarget.dataset.title);
    }
    if(!!_link && /^\/replaceWithNeed\/\d+/.test(_link)){
      var _id = _link.match(/^\/replaceWithNeed\/(\d+)/)[1];
      wx.navigateTo({
        url: './index?id='+_id + (!!_position ? '&tiaoPosition='+_position : ""),
        success: function(res){
          // success
        },
        fail: function() {
          // fail
        },
        complete: function() {
          // complete
        }
      })
    }
  },
  wxParseTagALongTap: function(_event){
    // console.log(_event);
  },
  wxParseTagBlockTap: function(_event){
    if(!!_event.currentTarget.dataset.id){
      this.setData({
        toView: _event.currentTarget.dataset.id
      });
      this.hideMask();
    }
  },
  selectTab: function(_event){
    this.setData({
      tabSelectIndex: _event.currentTarget.dataset.index
    });

    this.setData({
      detailInfo: this.data.detailInfo
    });
  },
  handtoptap: function(_event){
    _optEvent = _event;
    this.setData({
      showOpt:true,
      hideBottomOpts: !this.data.hideBottomOpts
    });
  },
  showErrorDialog: function(_event){
    this.setData({
      correctMaskHide: false,
      showErrorDialog: true,
      hideBottomOpts: !this.data.hideBottomOpts
    })
  },
  uploadUserFeedbackError: function(_event){

  },
  getUserSay: function(_event){
    _userSay = _event.detail.value;
  },
  getUserFeedback: function(_event){
    _userFeedback = _event.detail.value;
  },
  uploadUserBookMark: function(_event){
    if(!this.data.userInfo){
      wx.showToast({
        title: '需要先登录',
        icon: 'success',
        duration: 1000
      });
      return;
    }
    if(!_userSay){
      wx.showToast({
        title: '请填写内容',
        icon: 'success',
        duration: 1000
      });
      return;
    }

    var that = this;
    var _offsetTop = this.data.scrollTopCal + _saveEvent.detail.y;
    // 获取列表
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/save/law/bookmark`, //仅为示例，并非真实的接口地址
      data: {
        id: this.data.editBookMakrId,
        uid: this.data.userInfo.unionId,
        lid: this.data.id,
        x: !this.data.editBookMakrId ? _saveEvent.detail.x : 0,
        y: !this.data.editBookMakrId ?  _saveEvent.detail.y : 0,
        offsetTop: !this.data.editBookMakrId ? _offsetTop : 0,
        content: !this.data.editBookMakrId ? _saveEvent.currentTarget.dataset.c || "" : "",
        userSay: _userSay,
        phone: this.data.phone
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1000
        });

        for(var i=0; i<that.data.innerBookmarks.length; i++){
          if(that.data.innerBookmarks[i].id == that.data.editBookMakrId){
            if(!that.data.innerBookmarks[i].id){
              that.data.innerBookmarks[i].id = res.data.id;
              that.data.innerBookmarks[i].userSay = _userSay;
              that.data.innerBookmarks[i].x = _saveEvent.detail.x;
              that.data.innerBookmarks[i].y = _saveEvent.detail.y;
              that.data.innerBookmarks[i].offsetTop = _offsetTop;
              var _pos = _getBookMarkSize(that.data.innerBookmarks[i]);
              that.data.innerBookmarks[i].left = _pos.left;
              that.data.innerBookmarks[i].top = _pos.top;
              that.data.innerBookmarks[i].width = _pos.width;
              that.data.innerBookmarks[i].height = _pos.height;
              that.data.innerBookmarks[i].atleft = _pos.atleft;
              that.data.innerBookmarks[i].show = false;
              that.data.innerBookmarks[i].hide = false;
            }else{
              that.data.innerBookmarks[i].userSay = _userSay;
            }
            break;
          }
        }

        that.setData({
          bookMarkMaskHide: true,
          showBookMarkDialog: false,
          newBookMarkMaskHide: true,
          showNewBookMarkDialog: false,
          hideBottomOpts: true,
          userSay: "",
          editBookMakrId: null,
          innerBookmarks: that.data.innerBookmarks
        })
      },
      fail: function(res){
        console.log(res);
      }
    })
  },
  deleteUserBookMark: function(){
    if(!this.data.editBookMakrId) return;
    var that = this;
    wx.showModal({
      title: "提示",
      content: "是否删除这条笔记？",
      success: function(){
        wx.request({
          url: `${getApp().globalData.serverHost}/wx/delete/law/bookmark`, //仅为示例，并非真实的接口地址
          data: {
            id: that.data.editBookMakrId
          },
          method: "post",
          header: {
              'content-type': 'application/json'
          },
          success: function(res) {
            wx.hideToast();
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1000
            });
            for(var i=0; i<that.data.innerBookmarks.length; i++){
              if(that.data.innerBookmarks[i].id == that.data.editBookMakrId){
                that.data.innerBookmarks.splice(i,1);
              }
            }
            that.setData({
              innerBookmarks: that.data.innerBookmarks,
              bookMarkMaskHide: true,
              showBookMarkDialog: false,
              hideBottomOpts: true,
              editBookMakrId: null
            })
          },
          fail: function(res){
            console.log(res);
          }
        })
      }
    })
  },
  uploadUserFeedbackError: function(){
    if(!_userFeedback){
      wx.showToast({
        title: '请填写反馈内容',
        icon: 'success',
        duration: 1000
      });
      return;
    }
    var that = this;
    // 获取列表
    wx.request({
      url: `${getApp().globalData.serverHost}/wx/save/user/feedback`, //仅为示例，并非真实的接口地址
      data: {
        uid: this.data.userInfo.unionId,
        lid: this.data.id,
        content: _userFeedback
      },
      method: "post",
      header: {
          'content-type': 'application/json'
      },
      success: function(res) {
        wx.hideToast();
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1000
        });
        that.setData({
          correctMaskHide: true,
          showErrorDialog: false,
          userFeedback: ""
        })
      },
      fail: function(res){
        console.log(res);
      }
    })
  },
  showBookMarkContent(_event){
    var _index = _event.target.dataset.index;
    this.data.innerBookmarks[_index].show = true;
    this.setData({
      innerBookmarks: this.data.innerBookmarks,
      hideBottomOpts: true
    });
  },
  hideBookMarkContent(_event){
    var _index = _event.currentTarget.dataset.index;
    this.data.innerBookmarks[_index].show = false;
    this.setData({
      innerBookmarks: this.data.innerBookmarks,
      hideBottomOpts: true
    });
  },
  showbookMakrEditDialog: function(_event){
    var _index = _event.currentTarget.dataset.index;
    this.setData({
      userSay: this.data.innerBookmarks[_index].userSay,
      editBookMakrId: this.data.innerBookmarks[_index].id,
      showBookMarkDialog: true,
      bookMarkMaskHide: false,
      showDeleteBtn: true
    });
  },
  gotoBookMark: function(_event){
    var _index = _event.currentTarget.dataset.index;
    if(this.data.innerBookmarks[_index].offsetTop > 3*_screenHeight/4){
      this.setData({
        scrollTop: this.data.innerBookmarks[_index].offsetTop-_screenHeight/2
      });
    }
    this.data.innerBookmarks[_index].show = true;
    this.setData({
      innerBookmarks: this.data.innerBookmarks
    });
    this.hideMask();
  },
  onShareAppMessage: function () {
    return {
      title: this.data.name,
      path: 'pages/detail/index/index?id='+this.data.id
    }
  },
  searchInputChange: function(_event){
    _searchInputCnt = (_event.detail.value||"").replace(/^\s*|\s*$/g, "");
  },
  showSearch: function(){
    this.setData({
      searchShow: true
    });
  },
  hideSearch: function(){
    this.setData({
      searchShow: false,
      hideBottomOpts: true
    });
  },
  searchContentToUp: function(){
    if(this._handlerSearch() == -1){
      wx.showToast({
        title: '没有查到相关内容',
        icon: 'success',
        duration: 2000
      });
      return;
    }
    if(!this.data.hasShowSearchCount){
      this.setData({
        hasShowSearchCount: true
      });
      wx.showToast({
        title: '查找到'+_totalSearchedNo+'条记录',
        icon: 'success',
        duration: 2000
      });
    }
    if(_searchedIndex < 0){
      _searchedIndex = _totalSearchedNo;
    }
    _searchedIndex = _searchedIndex - 1;
    this.setData({
      toView: "userSearchedResult" + _searchedIndex
    })
  },  
  searchContentToDown: function(){
    if(this._handlerSearch() == -1){
      wx.showToast({
        title: '没有查到相关内容',
        icon: 'success',
        duration: 2000
      });
      return;
    }
    if(!this.data.hasShowSearchCount){
      this.setData({
        hasShowSearchCount: true
      });
      wx.showToast({
        title: '查找到'+_totalSearchedNo+'条记录',
        icon: 'success',
        duration: 2000
      });
    }
    if(_searchedIndex >= _totalSearchedNo-1){
      _searchedIndex = -1;
    }
    _searchedIndex = _searchedIndex + 1;
    this.setData({
      toView: "userSearchedResult" + _searchedIndex
    })
  },
  _handlerSearch: function(){
    if(_searchInputCnt != this.data.lastSearchInputCnt){
      this.setData({
        hasSearched: false
      })
    }
    if(!!this.data.hasSearched) return;

    this.data.originContent = this.data.originContent.replace(/<div\s*class="user-search-result"\s*id="userSearchedResult\d+"><\/div>/g, "")
    .replace(/<em\s*class="user-search-result">(.+?)<\/em>/g, function($0,$1){
      return $1;
    })
    var _reg = new RegExp('(?:<p(?:(?:\\s{1,}class="(?:[-\\w]+\\s*)+"{0,1})|(?:\\s{1,}id="[-\\w]+"){0,1})*>|<br>|<div(?:(?:\\s{1,}class="(?:[-\\w]+\\s*)+"{0,1})|(?:\\s{1,}id="[-\\w]+"){0,1})*>)(?:<\/p>|<\/div>)*(?:<a(?:(?:\\s{1,}class="(?:[-\\w]+\\s*)+"{0,1})|(?:\\s{1,}id="[-\\w]+")|(?:\\s{1,}name="[-\\w]+"){0,1})*>[\u4e00-\u9fa5\\s]+<\/a>)*\\s*(?:(?:[\u4e00-\u9fa5，。、\\s\\d]*)?)(' + _searchInputCnt + ")", "g");
    var _match = this.data.originContent.match(_reg);
    if(!_match) return -1;
    var _content = this.data.originContent.replace(_reg, function($0, $1){
      var _tmp = $0.replace($1,'<em class="user-search-result">' + $1 + '</em>');
      _tmp = '<div class="user-search-result" id="userSearchedResult'+ (_totalSearchedNo++) +'"></div>' + _tmp;
      return _tmp;
    });
    _searchedIndex = -1;
    this.setData({
      originContent: _content,
      lastSearchInputCnt: _searchInputCnt,
      hasSearched: true
    });
    WxParse.wxParse('content', 'html', this.data.originContent, this);
  },
  handlerScroll: function(_event){
    this.setData({
      newBookMarkMaskHide: true,
      showNewBookMarkDialog: false,
      scrollTopCal: _event.detail.scrollTop || 0
    })
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
    this.setData({
      maskHide: true,
      dialogHide: true
    })
  },
  onUnload:function(){
    // 页面关闭
    this.setData({
      maskHide: true,
      dialogHide: true
    })
  }
})